//
//  LZScanQRCodeFromCameraPresenter.m
//  laziz_Merchant
//
//  Created by xbn_iMac on 2016/12/17.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZScanQRCodeFromCameraPresenter.h"
#import <AVFoundation/AVFoundation.h>
#import "LZAlertView.h"

@interface LZScanQRCodeFromCameraPresenter ()<AVCaptureMetadataOutputObjectsDelegate>

@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;

@end

@implementation LZScanQRCodeFromCameraPresenter

/**
 *  @author LY, 16-07-28 17:07:01
 *
 *  创建照相机的session等相关控件以及设置扫描识别区域
 *
 */
- (void)createCameraWithScanCrop:(CGRect)frame andBaseView:(id)aView
{
    // 先校验相机权限
    if ([self checkCameraPermissions]) {
        if (self.session == nil) {
            self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
            
            // input
            self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
            
            
            // output
            self.output = [[AVCaptureMetadataOutput alloc]init];
            [self setupOutputScanCrop:frame andBaseView:aView];
            [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
            
            
            
            // session
            self.session = [[AVCaptureSession alloc]init];
            [self.session setSessionPreset:AVCaptureSessionPresetHigh];
            if ([self.session canAddInput:self.input])
            {
                [self.session addInput:self.input];
            }
            
            if ([self.session canAddOutput:self.output])
            {
                [self.session addOutput:self.output];
            }
            
            // 条码类型
            if (self.input) {
                self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
//                self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeCode39Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode39Mod43Code,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode93Code];
            }
            
            // preview
            
            UIView *v = aView;
            
            self.preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
            self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
            self.preview.frame = v.bounds;
            [v.layer insertSublayer:self.preview atIndex:0];
            
            //        [self sessionStart];
        }
    }
    else {
        LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"iphone_permissions_camera_remind", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"iphone_permissions_go_setting", nil),nil];
        [alert show];
        
        alert.clickButtonIndexBlock = ^(NSInteger index) {
            if (index == 1) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        };
    }
}

/* 校验相机权限 */
- (BOOL)checkCameraPermissions {
    NSString *mediaType = AVMediaTypeVideo;//读取媒体类型
    AVAuthorizationStatus authorStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];//读取设备授权状态
    if(authorStatus == AVAuthorizationStatusRestricted || authorStatus == AVAuthorizationStatusDenied){
        //无权限
        return NO;
    }
    return YES;
}

// session开始
-(void)sessionStart {
    [_session startRunning];
}

// session结束
-(void)sessionStop {
    [_session stopRunning];
}

-(void)dealloc {
    _session = nil;
    [_preview removeFromSuperlayer];
}


-(void)setupOutputScanCrop:(CGRect)cropRect andBaseView:(UIView *)aView {
    CGSize size = aView.bounds.size;
    
    CGFloat p1 = size.height/size.width;
    CGFloat p2 = 1920./1080.;  //使用了1080p的图像输出
    if (p1 < p2) {
        CGFloat fixHeight = SCREEN_WIDTH * 1920. / 1080.;
        CGFloat fixPadding = (fixHeight - size.height)/2;
        self.output.rectOfInterest = CGRectMake((cropRect.origin.y + fixPadding)/fixHeight,
                                                cropRect.origin.x/size.width,
                                                cropRect.size.height/fixHeight,
                                                cropRect.size.width/size.width);
    } else {
        CGFloat fixWidth = SCREEN_HEIGHT * 1080. / 1920.;
        CGFloat fixPadding = (fixWidth - size.width)/2;
        self.output.rectOfInterest = CGRectMake(cropRect.origin.y/size.height,
                                                (cropRect.origin.x + fixPadding)/fixWidth,
                                                cropRect.size.height/size.height,
                                                cropRect.size.width/fixWidth);
    }
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
    NSString *stringValue;
    
    if ([metadataObjects count] >0)
    {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        if ([metadataObject.type isEqualToString:AVMetadataObjectTypeQRCode]) {
            // This will never happen; nobody has ever scanned a QR code... ever
            NSLog(@"这是一个二维码：%@",stringValue);
        }
        else
        {
            NSLog(@"这是一个条形码：%@",stringValue);
            
        }
        [self sessionStop];
        [self dealResult:stringValue];
    }
    else
    {
        NSLog(@"没有结果======%@",stringValue);
        [self dealResult:nil];
    }
}

-(void)dealResult:(NSString*)aString {
    if (aString == nil) {
        if (self.CrameScanResult) {
            
            NSError *error = [[NSError alloc] initWithDomain:@"InvalidCode" code:100 userInfo:nil];
            
            self.CrameScanResult(nil,error);
        }
    }
    else {
        if (self.CrameScanResult) {
            self.CrameScanResult(aString,nil);
        }
    }
}

@end
